import { AxiosRequestConfig, AxiosResponse, AxiosError, Method } from 'axios'
import { useGlobalStore } from '@/stores/global'
import { useUserStore } from '@/stores/user'

export interface RespData<T = any> {
  errno: number
  data: T
  message?: string
}

export interface ListData<T> {
  list: T[]
  count: number
}

export interface UploadData {
  url: string
}

export interface SearchParamsData {
  pageIndex: number
  pageSize: number
  keyword: string
}

// interface ChannelProps {
//   id: string
//   name: string
//   status: 0 | 1 // 状态：0-删除 1-正常
// }

// id uuid author copiedCount coverImg desc title user isTemplate isHot isPublic createdAt latestPublishAt status orderIndex
export interface WorkDataProps {
  id: number
  uuid: string // 短链接 uuid
  title: string // 标题
  desc: string // 副标题，描述
  coverImg: string // 缩略图
  isTemplate: boolean // 是否模版
  isPublic: boolean // 是否公开到首页，默认 false，模版用
  isHot: boolean // 是否 hot, 默认 false，模版用
  author: string // 作者 username
  copiedCount: number // 被复制的次数
  status: 0 | 1 | 2 | 3 // 状态：0-删除 1-未发布 2-发布 3-管理员强制下线
  orderIndex: number // 排序参数
  createdAt: string
  latestPublishAt: string // 最近一次发布的时间
}

export type ICustomAxiosConfig = AxiosRequestConfig & { opName?: string }
export const baseAdminAPI = import.meta.env.VITE_BASE_ADMIN_API
export const baseStatAPI = import.meta.env.VITE_BASE_STAT_API

const instance = axios.create({
  // baseURL: baseAdminAPI,
  timeout: 2000 * 1000
})

instance.interceptors.request.use(config => {
  const global = useGlobalStore()
  const user = useUserStore()
  const newConfig = config as ICustomAxiosConfig
  global.setError({ status: false, message: '' })
  config.headers['Authorization'] = `Bearer ${user.token}`
  global.startLoading({ opName: newConfig.opName })
  return config
})
instance.interceptors.response.use(
  (response: AxiosResponse<RespData>) => {
    const global = useGlobalStore()
    const newConfig = response.config as ICustomAxiosConfig
    global.finishLoading({ opName: newConfig.opName })
    const { errno, message } = response.data
    if (errno !== 0) {
      let errorMessage = message
      if (errno === 11001) {
        errorMessage = '登录状态已过期 请重新登录'
        const user = useUserStore()
        user.logout()
      }
      global.setError({ status: true, message: errorMessage })
      return Promise.reject(response.data)
    }
    return response
  },
  (error: AxiosError) => {
    console.log(error)
    const global = useGlobalStore()
    const newConfig = error.config as ICustomAxiosConfig
    global.setError({ status: true, message: '服务器异常，请稍后再试' })
    global.finishLoading({ opName: newConfig.opName })
    return Promise.reject(error)
  }
)
export async function request<T = any>(url: string, method: Method, opName?: string): Promise<RespData<T>>
export async function request<T = any>(url: string, method: Method, data?: any, opName?: string): Promise<RespData<T>>
export async function request<T = any>(url: string, method: Method, data?: any, opName?: string) {
  if (data && typeof data === 'string') {
    opName = data
    data = {}
  }
  const newConfig: ICustomAxiosConfig = { method, opName }
  if (method === 'get' || method === 'GET') {
    newConfig.params = data
  } else {
    newConfig.data = data
  }
  const res = await instance<RespData<T>>(url, newConfig)
  return res.data
}

// 上传单个文件 支持 file blob
export async function uploadFile<T = { url: string }>(url: string, file: Blob, fileName = 'screenshot.png') {
  const newFile = file instanceof File ? file : new File([file], fileName)
  const formData = new FormData()
  formData.append(newFile.name, newFile)
  const res = await instance.post<RespData<T>>(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return res.data
}

// 上传多个文件
export async function uploadMultipartFiles<T = any>(url: string, data: { [key: string]: any }) {
  const keys = Object.keys(data)
  const formData = new FormData()
  keys.forEach(key => {
    formData.append(key, data[key])
  })
  const res = await instance.post<RespData<T>>(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return res.data
}

export default instance
